package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.NavUtils;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.SearchPersonMultipleListAdapter;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.entity.AttendanceSummaryStaffDialog;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.MessageContact;
import com.isunland.managesystem.utils.LocalSearch;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.ToastUtil;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 人员多选
 *
 * @author wu
 */
public class SearchPersonMultipleFragment extends BaseListFragment {
  public static final String EXTRA_VALUE = "com.isunland.managesystem.ui.extra_value";
  public static final String EXTRA_FROM =
      "com.isunland.managesystem.ui.SearchPersonListFragment.EXTRA_FORM";
  public static final String VALUE_TASK_COLLECT =
      "com.isunland.managesystem.ui.SearchPersonListFragment.VALUE_TASK_COLLECT";
  public static final String VALUE_COMMON =
      "com.isunland.managesystem.ui.SearchPersonListFragment.COMMON";
  public static final String EXTRA_DEPCODE =
      "com.isunland.managesystem.ui.SearchPersonListFragment.EXTRA_DEPCODE";
  public static final String EXTRA_JOB =
      "com.isunland.managesystem.ui.SearchPersonListFragment.EXTRA_JOB";
  public static final String EXTRA_NAME =
      "com.isunland.managesystem.ui.SearchPersonListFragment.EXTRA_NAME";
  public static final String EXTRA_ISPAGER =
      "com.isunland.managesystem.ui.SearchPersonListFragment.EXTRA_ISPAGER";
  private SearchPersonMultipleListAdapter mAdapter;
  private ArrayList<AttendanceSummaryStaffDialog.SummaryStaff> mList;//当前适配器数据,可能经过筛选.
  private ArrayList<AttendanceSummaryStaffDialog.SummaryStaff> mListOriginal;//全部数据

  private EditText mSearchEt;
  private String mFrom;
  private String mJobs;//反选的jobNOs.字符串多个用","拼接.
  private Menu mMenu;
  /** 是否已全选 */
  private boolean isSelectedAll;
  /** 是否重新创建适配器 */
  private boolean isRecreate;

  public static Fragment newInstance(String from) {
    return newInstance(from, "");
  }

  public static Fragment newInstance(String from, String jobNOs) {
    return newInstance(from, jobNOs, false);
  }

  /**
   * @param from 来自于,因为有几个不同的获取人员的方法.包括获取全部,获取考勤人员,获取上下级人员等.
   * @param jobNOs 如果需要反选,就传这个值,类似于10014,111111,1111222这样的形式.
   * @param isPager 人员选择列表名字不同，部门和人员两个tab页防止title错乱.
   */
  public static Fragment newInstance(String from, String jobNOs, boolean isPager) {
    Bundle bundle = new Bundle();
    bundle.putString(EXTRA_FROM, from);
    bundle.putString(EXTRA_JOB, jobNOs);
    bundle.putSerializable(EXTRA_ISPAGER, isPager);
    SearchPersonMultipleFragment fragment = new SearchPersonMultipleFragment();
    fragment.setArguments(bundle);
    return fragment;
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);

    mFrom = getArguments().getString(EXTRA_FROM);
    mJobs = getArguments().getString(EXTRA_JOB);
    boolean misPager = (boolean) getArguments().getSerializable(EXTRA_ISPAGER);
    mList = new ArrayList<>();
    if (NavUtils.getParentActivityName(mActivity) != null) {
      //noinspection ConstantConditions
      if (mActivity.getSupportActionBar() != null) {
        mActivity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        if (!misPager) {
          mActivity.getSupportActionBar().setTitle(R.string.selectPerson);
        }
      }
    }
  }

  @Override public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    mListview.setDivider(null);
    View header =
        getLayoutInflater(savedInstanceState).inflate(R.layout.header_search_person, mListview,
            false);
    mSearchEt = (EditText) header.findViewById(R.id.et_search_searchPersonHeader);
    mSearchEt.addTextChangedListener(new TextWatcher() {

      @Override public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (mListOriginal == null || mListOriginal.size() == 0) {
          return;
        }
        ArrayList<AttendanceSummaryStaffDialog.SummaryStaff> list;
        if (TextUtils.isEmpty(s)) {
          list = mListOriginal;
        } else {
          list = LocalSearch.searchSummaryStaff(s.toString(), mListOriginal);
        }
        setAdapter(list);
        mSearchEt.requestFocus();
      }

      @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {

      }

      @Override public void afterTextChanged(Editable s) {

      }
    });
    TextView mDepartmentTv = (TextView) header.findViewById(R.id.tv_department_searchPersonHeader);
    mDepartmentTv.setText(CurrentUser.newInstance(getActivity()).getDeptName());
    mListview.addHeaderView(header);

    //setAdapter(mList);
  }

  @Override public String getUrl() {
    if (mFrom != null && mFrom.equals(VALUE_TASK_COLLECT)) {
      //任务汇总人员，根据登录人工号获取人员
      return ApiConst.URL_GET_MANAGE_STAFF;
    } else if (mFrom != null && mFrom.equals(VALUE_COMMON)) {
      //所有人员
      return ApiConst.URL_QUERY_MEMBER;
    } else {
      //考情汇总人员
      return ApiConst.URL_GETATTENDANCE_STAFF;
    }
  }

  @Override public HashMap<String, String> getparameters() {
    HashMap<String, String> params = new HashMap<>();
    if (mFrom != null && mFrom.equals(VALUE_TASK_COLLECT)) {
      params.put("jobno", CurrentUser.newInstance(getActivity()).getJobNumber());
      params.put("ifContainDept", "false");
      params.put("ifContainStaff", "true");
      params.put("memCode", CurrentUser.newInstance(getActivity()).getMemberCode());
      return params;
    } else if (mFrom != null && mFrom.equals(VALUE_COMMON)) {
      params.put("type", "user");
      String memberCode = CurrentUser.newInstance(getActivity()).getMemberCode();
      params.put("orgCode", memberCode);
      return params;
    } else {
      return super.getparameters();
    }
  }

  @Override public void resolveResponse(String json) {
    ArrayList<AttendanceSummaryStaffDialog.SummaryStaff> rows;
    if (mFrom != null && mFrom.equals(VALUE_COMMON)) {
      Type listType = new TypeToken<ArrayList<MessageContact>>() {
      }.getType();

      ArrayList<MessageContact> messageDialogs = new Gson().fromJson(json, listType);
      rows = new AttendanceSummaryStaffDialog().turn(messageDialogs);
    } else {

      AttendanceSummaryStaffDialog original =
          new Gson().fromJson(json, AttendanceSummaryStaffDialog.class);
      rows = original.getDataList();
    }

    if (rows == null || rows.size() == 0) {
      ToastUtil.show(R.string.that_is_all);
      return;
    }

    mListOriginal = rows;
    setAdapter(rows);
  }

  private void setAdapter(List<AttendanceSummaryStaffDialog.SummaryStaff> list) {
    mList.clear();
    mList.addAll(list);
    //当原始列表有变化时重新创建adapter.
    if (mAdapter == null || isRecreate) {
      /** 如果原始数据为空,下次还需要重新创建*/
      isRecreate = (mListOriginal == null) || (mListOriginal.size() == 0);
      HashMap<AttendanceSummaryStaffDialog.SummaryStaff, Boolean> map = getSelectMap(mJobs, list);
      mAdapter = new SearchPersonMultipleListAdapter(getActivity(), mList, map);
      setListAdapter(mAdapter);
    }
    ((SearchPersonMultipleListAdapter) getListAdapter()).notifyDataSetChanged();
  }

  public HashMap<AttendanceSummaryStaffDialog.SummaryStaff, Boolean> getSelectMap(String jobNOs,
      List<AttendanceSummaryStaffDialog.SummaryStaff> list) {
    if (TextUtils.isEmpty(jobNOs) || list == null) return null;
    HashMap<AttendanceSummaryStaffDialog.SummaryStaff, Boolean> map = new HashMap<>();
    ArrayList<String> splitList = MyStringUtil.splitStr(jobNOs, MyStringUtil.COMMA);
    if (splitList == null) return map;
    for (AttendanceSummaryStaffDialog.SummaryStaff item : list) {
      if (splitList.contains(item.getJobNo())) {
        map.put(item, true);
      }
    }
    return map;
  }

  public void updateItems(String query) {

    // 直接通过中文人名来进行搜索
    ArrayList<AttendanceSummaryStaffDialog.SummaryStaff> listNames = new ArrayList<>();// 获取人名
    String str;
    String deptStr;
    for (int i = 0; i < mListOriginal.size(); i++) {
      str = mListOriginal.get(i).getName();
      deptStr = mListOriginal.get(i).getDeptName();
      if (str.contains(query) || deptStr.contains(query)) {
        listNames.add(mListOriginal.get(i));
      }
    }

    setAdapter(listNames);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      // 响应返回图标
      case android.R.id.home:

        getActivity().finish();
        return true;

      case R.id.menu_item_confirm:
        if (mListOriginal == null) return false;
        //如果网络请求未完成,adapter==null.
        if (mAdapter == null) return false;
        StringBuilder jobNos = new StringBuilder();
        StringBuilder names = new StringBuilder();
        StringBuilder deptCodes = new StringBuilder();
        for (AttendanceSummaryStaffDialog.SummaryStaff staff : mListOriginal) {
          if (mAdapter.isCheckedItem(staff)) {
            jobNos.append(staff.getJobNo()).append(MyStringUtil.COMMA);
            names.append(staff.getName()).append(MyStringUtil.COMMA);
            deptCodes.append(staff.getDeptCode()).append(MyStringUtil.COMMA);
          }
        }
        Intent i = new Intent();
        i.putExtra(EXTRA_JOB, MyStringUtil.substring(jobNos.toString(), 0, jobNos.length() - 1));
        i.putExtra(EXTRA_NAME, MyStringUtil.substring(names.toString(), 0, names.length() - 1));
        i.putExtra(EXTRA_DEPCODE,
            MyStringUtil.substring(deptCodes.toString(), 0, deptCodes.length() - 1));

        getActivity().setResult(Activity.RESULT_OK, i);
        getActivity().finish();
        return true;
      //全选
      case R.id.menu_item_bat:
        //如果网络请求未完成,adapter==null.
        if (mAdapter == null) return false;
        if (isSelectedAll) {
          //当前状态为已全选,点击按钮,执行反选.
          mAdapter.deSetlectAll();
          isSelectedAll = false;
          mMenu.getItem(0).setIcon(R.drawable.bat);
          mMenu.getItem(0).setTitle(R.string.selectAll);
        } else {
          //默认未全选.执行全选.并更新按钮状态为已全选,按钮为取消全选.
          mAdapter.setlectAll();
          isSelectedAll = true;
          mMenu.getItem(0).setIcon(R.drawable.cancle);
          mMenu.getItem(0).setTitle(R.string.cancel);
        }

        break;
      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    //        inflater.inflate(R.menu.menu_confirm, menu);
    inflater.inflate(R.menu.menu_multi_confirm, menu);
    mMenu = menu;
    super.onCreateOptionsMenu(menu, inflater);
  }
}
